package com.antdesignbackend.backend.controller;

import com.antdesignbackend.backend.animalNumber.entity.AnimalNumber;
import com.antdesignbackend.backend.animalNumber.service.AnimalNumberService;
import com.antdesignbackend.backend.aop.AuthToken;
import com.antdesignbackend.backend.common.CalendarDate;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.common.web.BaseController;
import com.antdesignbackend.backend.entity.Enterprise;
import com.antdesignbackend.backend.entity.Production;
import com.antdesignbackend.backend.entity.Reproduction;
import com.antdesignbackend.backend.entity.entityVo.MonthReportRecordVo;
import com.antdesignbackend.backend.service.EnterpriseService;
import com.antdesignbackend.backend.service.MonthReportRecordService;
import com.antdesignbackend.backend.service.ProductionService;
import com.antdesignbackend.backend.service.ReproductionService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/monthReportRecord")
public class MonthReportRecordController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    ReturnVO result = new ReturnVO();
    @Autowired
    MonthReportRecordService monthReportRecordService;
    @Autowired
    AnimalNumberService animalNumberService;
    @Autowired
    EnterpriseService enterpriseService;
    @Autowired
    ProductionService productionService;
    @Autowired
    ReproductionService reproductionService;
    /**
     * 月报表记录
     */
    @GetMapping("/index")
    @AuthToken
    public String index() {
        return "records/monthReportRecord/index";
    }

    /**
     * 表格查询
     */
    @PostMapping("/tableSearch")
    @ResponseBody
    public ReturnVO tableSearch(@RequestBody MonthReportRecordVo monthReportRecordVo) throws NoSuchMethodException, SecurityException,
            IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        List<MonthReportRecordVo> monthReportRecordVos = new ArrayList<>();
        QueryWrapper<MonthReportRecordVo> wrapper = new QueryWrapper<>();
        if (monthReportRecordVo.getReportMonth() != null && !monthReportRecordVo.getReportMonth().equals("")) {
            wrapper.eq("a.reportMonth", monthReportRecordVo.getReportMonth());
        }
        wrapper.orderByDesc("a.reportMonth");
        wrapper.eq("a.eid", getLoginEnterpriseId());
        //先统计满足条件的数据总数，因为sql 不包括排序
        int total = monthReportRecordService.count(wrapper);
        result.setTotal(total);
        //再查询
        if (total >= 0) {
            monthReportRecordVos = monthReportRecordService.search(wrapper, new Page<>(monthReportRecordVo.getPageIndex(), monthReportRecordVo.getPageSize()));
        }
        result.setData(monthReportRecordVos);
        return result;
    }

    /**
     * 表格查询(显示最新的一条数据)
     */
    @PostMapping("/tableSearch2")
    @ResponseBody
    public ReturnVO tableSearch2(@RequestBody MonthReportRecordVo monthReportRecordVo) throws NoSuchMethodException, SecurityException,
            IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        List<MonthReportRecordVo> monthReportRecordVos = new ArrayList<>();
        QueryWrapper<MonthReportRecordVo> wrapper = new QueryWrapper<>();
        if (monthReportRecordVo.getReportMonth() != null && !monthReportRecordVo.getReportMonth().equals("")) {
            wrapper.eq("a.reportMonth", monthReportRecordVo.getReportMonth());
        }
        wrapper.orderByDesc("a.reportMonth");
        wrapper.eq("a.eid", getLoginEnterpriseId());
//        //先统计满足条件的数据总数，因为sql 不包括排序
        int total = monthReportRecordService.count(wrapper);
//        result.setTotal(total);
        //再查询
        if (total >= 0) {
            monthReportRecordVos = monthReportRecordService.search(wrapper, new Page<>(monthReportRecordVo.getPageIndex(), monthReportRecordVo.getPageSize()));
        }
        result.setData(monthReportRecordVos.get(0));
        return result;
    }

    /**
     * 表格查询(显示最新的一条数据月报记录和预警信息)
     */
    @PostMapping("/tableSearch3")
    @ResponseBody
    public ReturnVO tableSearch3(@RequestBody MonthReportRecordVo monthReportRecordVo) throws NoSuchMethodException, SecurityException,
            IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        Map<String,Object> map=new HashMap<>();

        //预警信息
        Enterprise enterprise = enterpriseService.getById(getLoginEnterpriseId());
        //获得企业存栏数
        int live = 0;
        QueryWrapper<AnimalNumber> wrapper = new QueryWrapper<>();
        wrapper.eq("Eid",enterprise.getEnterpriseId());
        List<AnimalNumber> list = animalNumberService.list(wrapper);
        if(!list.isEmpty()){
            for (AnimalNumber animalNumber:list){
                live += animalNumber.getSpecies()
                        + animalNumber.getReserve()
                        + animalNumber.getMenstruation()
                        + animalNumber.getLactation()
                        + animalNumber.getConservation()
                        + animalNumber.getCommodity()
                        + animalNumber.getLivestock();
            }
        }

        /**
         * 计算本季度死淘率 季度   死淘 / 调入 + 调出 + 死淘 + 出生
         */
        double mortality =0.00;
        Double m = 0.0;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        //得到本季度第一天时间
        Date firstQuarter = CalendarDate.getFirstDateOfSeason(new Date());
        //得到本季度最后一天时间
        Date lastQuarter = CalendarDate.getLastDateOfSeason(new Date());
        //获得本季度的生产记录
        QueryWrapper<Production> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("eid", getLoginEnterpriseId());
        queryWrapper.between("createTime", firstQuarter, lastQuarter);
        List<Production> productionList = productionService.list(queryWrapper);
        if (productionList.size() > 0) {
            //死淘
            Double dead = 0.0;
            //总计
            Double sum = 0.0;
            for (Production production : productionList) {
                //死淘
                if ("死淘".equals(production.getSituation())){
                    dead += production.getMale() + production.getFemale()
                            + production.getBreedFemale() + production.getLactation()
                            + production.getConservation() + production.getGrow();
                }
                sum += production.getMale() + production.getFemale()
                        + production.getBreedFemale() + production.getLactation()
                        + production.getConservation() + production.getGrow();
            }
            //计算死淘率
            m = dead * 100.0 / sum;
            map.put("mortalityNum",dead.intValue());                                 //本季度死淘数
        }
        mortality = m;
        /**
         * 计算预产期超出数 当前时间大于预产时间，并且分娩日期为null
         */
        QueryWrapper<Reproduction> reproductionQueryWrapper = new QueryWrapper<>();
        reproductionQueryWrapper.eq("eid",getLoginEnterpriseId());
        reproductionQueryWrapper.lt("productionTime",new Date()).isNull("deliveryTime");
        List<Reproduction> reproductionList = reproductionService.list(reproductionQueryWrapper);
//        enterpriseVo.setEnterpriseName(enterprise.getEnterpriseName());
        map.put("enterpriseName",enterprise.getEnterpriseName());       //企业名称
//        enterpriseVo.setAnimal(enterprise.getAnimal());
        map.put("animal",enterprise.getAnimal());                       //饲养动物种类
//        enterpriseVo.setLive(live);
        map.put("live",live);                                           //存栏数
//        enterpriseVo.setMortality(mortality);
        map.put("mortality",mortality);                                 //本季度死淘率

//        enterpriseVo.setOut(reproductionList.size());
        map.put("out",reproductionList.size());                         //预产期超出数

        //月报信息
        List<MonthReportRecordVo> monthReportRecordVos = new ArrayList<>();
        QueryWrapper<MonthReportRecordVo> wrapper1 = new QueryWrapper<>();
//        if (monthReportRecordVo.getReportMonth() != null && !monthReportRecordVo.getReportMonth().equals("")) {
//            wrapper1.eq("a.reportMonth", monthReportRecordVo.getReportMonth());
//        }
        wrapper1.orderByDesc("a.reportMonth");
        wrapper1.eq("a.eid", getLoginEnterpriseId());
//        //先统计满足条件的数据总数，因为sql 不包括排序
        int total = monthReportRecordService.count(wrapper1);
//        result.setTotal(total);
        //再查询
        if (total >= 0) {
            monthReportRecordVos = monthReportRecordService.search(wrapper1, new Page<>(monthReportRecordVo.getPageIndex(), monthReportRecordVo.getPageSize()));

            System.out.println("查出的最新一条月报信息为"+monthReportRecordVos.get(0)+"合计为"+monthReportRecordVos.get(0).getLivestockSum());
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM");
            map.put("reportMonth",simpleDateFormat.format(monthReportRecordVos.get(0).getReportMonth()));                //上报年月
            map.put("livestockSum",monthReportRecordVos.get(0).getLivestockSum());              //存栏数合计
            map.put("maleLivestock",monthReportRecordVos.get(0).getMaleLivestock());            //种公畜存栏数
            map.put("femaleLivestock",monthReportRecordVos.get(0).getFemaleLivestock());        //后备母畜存栏数
            map.put("breedFemaleLivestock",monthReportRecordVos.get(0).getBreedFemaleLivestock());        //能繁母畜存栏数
            map.put("lactationLivestock",monthReportRecordVos.get(0).getLactationLivestock());        //哺乳牲畜存栏数
            map.put("conservationLivestock",monthReportRecordVos.get(0).getConservationLivestock());        //保育牲畜存栏数
            map.put("growLivestock",monthReportRecordVos.get(0).getGrowLivestock());        //育成牲畜存栏数
            map.put("fetusNumber",monthReportRecordVos.get(0).getFetusNumber());        //产仔胎数
            map.put("litterNumber",monthReportRecordVos.get(0).getLitterNumber());        //产仔数
            map.put("publicationSum",monthReportRecordVos.get(0).getPublicationSum());        //出栏数合计
            map.put("malePublication",monthReportRecordVos.get(0).getMalePublication());                //种公畜出栏数
            map.put("femalePublication",monthReportRecordVos.get(0).getFemalePublication());                //后备母畜出栏数
            map.put("breedFemalePublication",monthReportRecordVos.get(0).getBreedFemalePublication());       //能繁母畜出栏数
            map.put("lactationPublication",monthReportRecordVos.get(0).getLactationPublication());           //哺乳牲畜出栏数
            map.put("conservationPublication",monthReportRecordVos.get(0).getConservationPublication());    //保育牲畜出栏数
            map.put("growPublication",monthReportRecordVos.get(0).getGrowPublication());                //育成牲畜出栏数
            map.put("harmlessSum",monthReportRecordVos.get(0).getHarmlessSum());                //无害化处理数合计
            map.put("maleHarmless",monthReportRecordVos.get(0).getMaleHarmless());              //种公畜无害化处理数
            map.put("femaleHarmless",monthReportRecordVos.get(0).getFemaleHarmless());          //后备母畜无害化处理数
            map.put("breedFemaleHarmless",monthReportRecordVos.get(0).getBreedFemaleHarmless());         //能繁母畜无害化处理数
            map.put("lactationHarmless",monthReportRecordVos.get(0).getLactationHarmless());              //哺乳牲畜无害化处理数
            map.put("conservationHarmless",monthReportRecordVos.get(0).getConservationHarmless());        //保育牲畜无害化处理数
            map.put("growHarmless",monthReportRecordVos.get(0).getGrowHarmless());              //育成牲畜无害化处理数
        }
//        result.setData(monthReportRecordVos.get(0));

        /**
         * 存栏数变化百分比
         */
        if (monthReportRecordVos.size() > 2){
            Double thisMouth=Double.valueOf(monthReportRecordVos.get(0).getLivestockSum());
            Double beforeMouth=Double.valueOf(monthReportRecordVos.get(1).getLivestockSum());
            Double livestockSumChange=(thisMouth-beforeMouth)/beforeMouth*100;
            DecimalFormat df  = new DecimalFormat("###.00");
            map.put("livestockSumChange",df.format(livestockSumChange));
        } else{
            map.put("livestockSumChange",0);
        }
        result.setData(map);
        return result;
    }
    @PostMapping("/tableSearchMe/{eid}")
    @ResponseBody
    public ReturnVO tableSearchMe(@PathVariable("eid") int eid) throws NoSuchMethodException, SecurityException,
            IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        List<MonthReportRecordVo> monthReportRecordVos = new ArrayList<>();
        QueryWrapper<MonthReportRecordVo> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("a.reportMonth");
        wrapper.eq("a.eid", eid);
        //先统计满足条件的数据总数，因为sql 不包括排序
        int total = monthReportRecordService.count(wrapper);
        result.setTotal(total);
        //再查询
        if (total >= 0) {
            monthReportRecordVos = monthReportRecordService.search(wrapper, new Page<>(1, 10));
        }
        result.setData(monthReportRecordVos);
        return result;
    }

    /**
     * 根据id删除
     */
    @DeleteMapping("/deleteById/{id}")
    @ResponseBody
    public ReturnVO deleteById(@PathVariable Serializable id) {
        result = new ReturnVO();
        if (monthReportRecordService.removeById(Integer.parseInt(id.toString())) == true) {
            result.setMessage("删除成功");
        } else {
            result.setMessage("删除失败");
            result.setCode("0");
        }
        return result;
    }

    /**
     * 修改/新增操作的保存
     */
    @GetMapping("/save")
    @ResponseBody
    @AuthToken
    public void save() throws Exception {

    }

}